package com.hero.herocat.handler;

import com.hero.herocat.DefaultCustomServlet;
import com.hero.herocat.HttpCustomRequest;
import com.hero.herocat.HttpServletResponse;
import com.hero.herocat.ServerResource;
import com.hero.servlet.HeroRequest;
import com.hero.servlet.HeroResponse;
import com.hero.servlet.HeroServlet;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * servlet处理分派
 *
 * @author linhui
 */
public class ServletHandler implements IHandler {

    private Map<String, HeroServlet> nameToServletMap = new ConcurrentHashMap<>();
    private Map<String, String> nameToClassNameMap = new HashMap<>();

    private ServerResource serverResource;

    public void init(ServerResource serverResource) {
        this.serverResource = serverResource;
        String basePackage = serverResource.getString("basePackage");
        cacheClassName(basePackage);
    }

    private void cacheClassName(String basePackage) {
        URL resource = this.getClass().getClassLoader()
                .getResource(basePackage.replaceAll("\\.", "/"));
        if (resource == null) {
            return;
        }
        /// decode防止中文路径报错
        File dir = new File(URLDecoder.decode(resource.getFile()));

        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {

                cacheClassName(basePackage + "." + file.getName());
            } else if (file.getName().endsWith(".class")) {
                String simpleClassName = file.getName().replace(".class", "").trim();

                nameToClassNameMap.put(simpleClassName.toLowerCase(), basePackage + "." + simpleClassName);
            }
        }

    }

    @Override
    public boolean needHandle(String name) {
        /// 默认的都处理
        return true;
    }

    @Override
    public void handle(HeroRequest request, HeroResponse response) throws Exception {
        HeroServlet servlet = new DefaultCustomServlet();

        String servletName = ((HttpCustomRequest) request).getPathName();
        if (nameToServletMap.containsKey(servletName)) {
            servlet = nameToServletMap.get(servletName);
        } else if (nameToClassNameMap.containsKey(servletName)) {

            synchronized (this) {
                if (nameToServletMap.get(servletName) == null) {
                    // 获取当前Servlet的全限定性类名
                    String className = nameToClassNameMap.get(servletName);
                    // 使用反射机制创建Servlet实例
                    try {
                        servlet = (HeroServlet) Class.forName(className).newInstance();
                        // 将Servlet实例写入到nameToServletMap
                        nameToServletMap.put(servletName, servlet);
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }

                }
            }
        }


        if (request.getMethod().equalsIgnoreCase("GET")) {
            servlet.doGet(request, response);
        } else if (request.getMethod().equalsIgnoreCase("POST")) {
            servlet.doPost(request, response);
        }
        ((HttpServletResponse) response).close();
    }

}
